package com.xbq.exceleditor.adapter

import androidx.core.view.isVisible
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.xbq.exceleditor.R
import com.xbq.exceleditor.databinding.ItemCollectionPlayListBinding
import com.xbq.exceleditor.utils.isFreeOrVip
import com.xbq.xbqsdk.net.officeeditor.vo.OfficeVideo
import com.xbq.xbqsdk.net.userCache
import javax.inject.Inject

/**
 * Author: liaohaiping
 * Time: 2021-01-20
 * Description:
 */
class CollectionPlayListAdapter @Inject constructor():
    BaseQuickAdapter<OfficeVideo, BaseViewHolder>(R.layout.item_collection_play_list) {
    var selectedVideo: OfficeVideo? = null

    private var needPay = !userCache.isFreeOrVip()

    fun refreshNeedPay(){
        needPay = !userCache.isFreeOrVip()
        notifyDataSetChanged()
    }

    override fun convert(
        holder: BaseViewHolder,
        item: OfficeVideo,
    ) {
        ItemCollectionPlayListBinding.bind(holder.itemView).let {
            it.tvIndex.text = item.index.toString()
            it.vipLogo.isVisible = needPay && item.isNeedVip
            if (selectedVideo?.id == item.id) {
                it.root.setBackgroundResource(R.drawable.bg_button_rect_primary)
            } else {
                it.root.setBackgroundResource(R.drawable.bg_button_rect_gray)
            }
        }
    }

    fun select(video: OfficeVideo) {
        val old = selectedVideo
        selectedVideo = video
        if (old != null) {
            notifyData(old)
        }
        notifyData(video)
    }

    private fun notifyData(old: OfficeVideo) {
        var index = data.indexOfFirst { old.id == it.id }
        if (index != -1) {
            notifyItemChanged(index)
        }
    }

    fun selectedIndex(): Int {
        return data.indexOfFirst { it.id == selectedVideo?.id }
    }

}